package org.codingq92.basic.io.bio;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

/**
 * BIO传输文件Client
 *
 * @author: CodingQ92
 * @date: 2025/6/24 21:12
 */
public class BIOFileClient {
    public static void main(String[] args) {
        // 启动client
        List<String> list = new ArrayList<>();
        list.add("/Users/smyxmac/Documents/workspace/ideaSpace/HandWritten/src/main/resources/0xProtoNerdFont-Regular.ttf");
        list.add("/Users/smyxmac/Documents/workspace/ideaSpace/HandWritten/src/main/resources/小学汉字.txt");
        client(list.get(1));
    }

    private static void client(String filePath) {
        try (InputStream is = new FileInputStream(filePath)) {
            Socket socket = new Socket("127.0.0.1", 18000);
            OutputStream outputStream = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(outputStream);
            // 获取文件类型
            int i = filePath.lastIndexOf(".");
            dos.writeUTF(filePath.substring(i + 1));
            // 读取文件内容 每次读取1024字节
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) > -1) {
                dos.write(bytes, 0, len);
            }
            dos.flush();
            socket.shutdownOutput(); // 这个一定要加 不然 等client结束 server还在while循环去获取数据就卡住了 无法结束～
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
